import os

from sc_engine.apps import messages as msgs

from sc_engine.repositories import Repository, use
from sc_engine.repositories.stores import PickleFileStore


def make_app(app_name, root_config, config):
    data_directory = root_config['data_directory']

    store_filename = os.path.join(data_directory, app_name)
    store = PickleFileStore(store_filename)
    repo = Repository(store)

    app = UnknownDataApp(repo)

    return {
        msgs.PlayerDataAnnouncement: app.player_data_announcement,
        msgs.MapDataAnnouncement: app.map_data_announcement,
        msgs.GameDataAnnouncement: app.game_data_announcement,
    }

class UnknownDataApp(object):
    """Request data for unknown maps and players as they are discovered.

    As data is being fetched from the schedule, whenever we see a player or map
    we have no data on, send out messages to start collecting data on those
    players or maps.
    """

    def __init__(self, repo):
        self.repo = repo

    @use('repo', 'players')
    def player_data_announcement(self, msg, players):
        players[msg.player_id] = 0

    @use('repo', 'maps')
    def map_data_announcement(self, msg, maps):
        maps[msg.map_id] = 0

    @use('repo', 'players', 'maps')
    def game_data_announcement(self, msg, players, maps):
        out = []
    
        if msg.player_one and msg.player_one not in players:
            out.append(msgs.PlayerDataRequested(msg.player_one))

        if msg.player_two and msg.player_two not in players:
            out.append(msgs.PlayerDataRequested(msg.player_two))

        if msg.game_map and msg.game_map not in maps:
            out.append(msgs.MapDataRequested(msg.game_map))
    
        return out

